package com.oreilly.ez.web;

import com.oreilly.ez.base.R;
import com.oreilly.ez.entity.Account;
import com.oreilly.ez.entity.SysUser;
import com.oreilly.ez.repo.AccountRepo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Example;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.util.Assert;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestHeader;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpSession;
import javax.validation.Valid;
import java.util.Date;
import java.util.Optional;

@RestController
@RequestMapping("/accounts")
@Validated
public class AccountCtrl  extends BaseCtrl<Account>{

    @Autowired
    private AccountRepo accountRepo;


    @PostMapping

    // @RequestHeader(value = "x-token") String token ,
    public Object save( @RequestBody @Valid Account account){

        Assert.notNull(account,"account 不能为空");

        SysUser user = sessionUser();
        account.setUserPin(user.getPin());

        accountRepo.save(account);
        return R.ok(account);

    }

    @GetMapping
    public Object find(Account account, Pageable pageable){


        SysUser user = sessionUser();

        if(account == null){
            account = new Account();
        }

        String pin = user.getPin();
        account.setUserPin(pin);
        Example<Account> example = Example.of(account);

        Page<Account> page = accountRepo.findAll(example, pageable);

        return R.ok(page);
    }



    @Override
    public Object findOne(@PathVariable  Integer id){

        Assert.notNull(id, "id required");
        Optional<Account> account = accountRepo.findById(id);
        return R.ok(account);
    }



    @Override
    public Object delete(@PathVariable  Integer id){

        Assert.notNull(id, "id required");
        accountRepo.deleteById(id);
        return R.ok("");
    }


    @GetMapping("/excel-export/{id}")
    public Object excelExport(@PathVariable  Integer id){

        Assert.notNull(id, "id required");
        accountRepo.deleteById(id);
        return R.ok("");
    }




}
